export function changeColor(color, tab = "#") {
    if (color.indexOf("#") > -1) return color;
    if (color == "") return "transparent";
    return color.toString().replace("0x", tab);
}

export function colorHex(color){
  var that = color;
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  if (/^(rgb|RGB)/.test(that)) {
      var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
      var strHex = "#";
      for (var i=0; i<aColor.length; i++) {
          var hex = Number(aColor[i]).toString(16);
          if (hex.length < 2) {
              hex = '0' + hex;    
          }
          strHex += hex;
      }
      if (strHex.length !== 7) {
          strHex = that;    
      }
      return strHex;
  } else if (reg.test(that)) {
      var aNum = that.replace(/#/,"").split("");
      if (aNum.length === 6) {
          return that;    
      } else if(aNum.length === 3) {
          var numHex = "#";
          for (var i=0; i<aNum.length; i+=1) {
              numHex += (aNum[i] + aNum[i]);
          }
          return numHex;
      }
  }
  return that;
}


export function genId(length) {
    return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}

export function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

export function downloadFile(url, name = "") {
  var a = document.createElement("a");
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
}

export function downloadFileByBase64(base64, name) {
  var myBlob = dataURLtoBlob(base64);
  var myUrl = URL.createObjectURL(myBlob);
  downloadFile(myUrl, name);
}

export function colourBlend(c1, c2, ratio){
    ratio = Math.max(Math.min(Number(ratio), 1), 0)
    let r1 = parseInt(c1.substring(2, 4), 16)
    let g1 = parseInt(c1.substring(4, 6), 16)
    let b1 = parseInt(c1.substring(6, 8), 16)
    let r2 = parseInt(c2.substring(2, 4), 16)
    let g2 = parseInt(c2.substring(4, 6), 16)
    let b2 = parseInt(c2.substring(6, 8), 16)
    let r = Math.round(r1 * (1 - ratio) + r2 * ratio)
    let g = Math.round(g1 * (1 - ratio) + g2 * ratio)
    let b = Math.round(b1 * (1 - ratio) + b2 * ratio)
    r = ('0' + (r || 0).toString(16)).slice(-2)
    g = ('0' + (g || 0).toString(16)).slice(-2)
    b = ('0' + (b || 0).toString(16)).slice(-2)
    return '0x' + r + g + b
}

export function random(lower, upper){
	lower = +lower || 0
	upper = +upper || 0
	return Math.random() * (upper - lower) + lower;
}